import { Button, message, Space } from 'antd'
import cs from 'classnames'
import dayjs from 'dayjs'
import { debounce } from 'lodash'
import { useContext, useEffect, useState } from 'react'
import { useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'
import { CSSTransition } from 'react-transition-group'

import DashboardBg from '@/assets/dashboard-bg.png'
import DashboardBgx2 from '@/assets/dashboard-bgx2.png'
import DashboardBgx3 from '@/assets/dashboard-bgx3.png'
import DashboardBgx4 from '@/assets/dashboard-bgx4.png'
import SvgIcon from '@/components/SvgIcon'
import { GlobalContext } from '@/context'
import store, { GlobalState } from '@/store'
import { get, set } from '@/utils/storage'

import locale from './locale'
import styles from './style/index.module.less'

function Dashboard() {
  const { dashboardNum, orgName } = useSelector((state: GlobalState) => state)
  // 选择的系统语言
  const { setLang, systemLanguage } = useContext(GlobalContext)
  const route = useHistory()
  const messageKey = 'updatable'

  const initError = () => {
    if (systemLanguage === 'ar-EG') {
      return `فشلت التهيئة. يرجى الاتصال بشبكة ${orgName} للمحاولة مرة أخرى.`
    } else {
      return `Initialization failed. Please connect to the ${orgName} network to try again.`
    }
  }

  const toHome = (lang: string) => {
    setLang(lang == 'en-US' ? 'en-US' : 'ar-EG')
    const isCheck = get('isCheck')
    const isDeviceError = get('isDeviceError')

    if (!!isDeviceError) {
      message.open({
        key: messageKey,
        type: 'error',
        content: locale[systemLanguage]['asyncData.device.error'],
        duration: 3,
      })
      return
    }
    if (!isCheck) {
      message.open({
        key: messageKey,
        type: 'error',
        content: initError(),
        duration: 3,
      })
      return
    }
    route.push('/home')
  }

  const close = () => {
    set('closeTime', dayjs().format('YYYY-MM-DD'))
    store.dispatch({
      type: 'update-dashboardNum',
      payload: {
        dashboardNum: 0,
      },
    })
  }

  const [bg, setBg] = useState<any>(DashboardBg)
  const initBg = debounce(() => {
    const px = document.body.clientWidth * window.devicePixelRatio
    // 1440,2880,4320,5760
    if (px <= 1440) {
      setBg(DashboardBg)
    }
    if (px <= 2880 && px > 1440) {
      setBg(DashboardBgx2)
    }
    if (px <= 4320 && px > 2880) {
      setBg(DashboardBgx3)
    }
    if (px > 4320) {
      setBg(DashboardBgx4)
    }
  }, 200)
  useEffect(() => {
    initBg()
    window.addEventListener('resize', initBg)
    return () => {
      window.removeEventListener('resize', initBg)
    }
  }, [])

  return (
    <div className={cs('w-full h-screen flex relative', 'ltr')}>
      {/* 弹窗 */}
      <CSSTransition in={dashboardNum != 0} classNames={'fade'} timeout={300} unmountOnExit>
        <div className={cs(styles['tips'])}>
          <div className={cs(styles['tips-wrapper'])}>
            <div>
              <SvgIcon name="tips" className=" w-12 h-12" />
            </div>
            <div className=" pl-6 pr-8">
              <div className="Cairo text-sm font-medium text-[#1D2129] text-right">
                {dashboardNum} التحقيقات المراد مزامنتها. اتصل بشبكة {orgName} لبدء المزامنة.
              </div>
              <div className="Avenir text-sm font-medium text-[#1D2129]">
                {dashboardNum} investigation(s) to be synced. Connect to {orgName} network to start
                syncing.
              </div>
            </div>
            <div className={cs(' absolute top-4 right-4 cursor-pointer')} onClick={() => close()}>
              <SvgIcon name="close" className=" w-4 h-4 text-[#BFBFBF]" />
            </div>
          </div>
        </div>
      </CSSTransition>
      {/* <img className="w-full" src={DashboardBg} /> */}
      <div className="w-full h-full overflow-hidden text-[0]">
        <img
          className="w-full"
          style={{
            width: '100%',
            height: '100%',
            objectFit: 'cover' /*保持原有尺寸比例，内容被缩放。*/,
          }}
          src={bg}
        />
      </div>

      <div className={cs(' absolute h-full w-full top-0 left-0  flex z-50 overflow-hidden')}>
        <div className={cs('flex-1 flex flex-col items-center justify-center z-10')}>
          <div>
            <SvgIcon name="dashboard-logo" className=" w-36 h-16" />
            <div className={cs(' font-medium text-[60px] Roboto text-white pt-12')}>
              SAFEGUARDING
            </div>
            <div className={cs(' font-medium text-[60px] Roboto text-white ')}>PUBLIC FUNDS</div>
            <div className={cs('Cairo font-medium text-[40px]  text-white pb-12')}>
              حماية الأموال العامة
            </div>
            <Space size={20}>
              <Button
                type="primary"
                ghost
                shape="round"
                className={styles['button']}
                onClick={() => toHome('en-US')}
              >
                English
              </Button>
              <Button
                type="primary"
                ghost
                shape="round"
                className={cs(styles['button'], 'Cairo')}
                onClick={() => toHome('ar-EG')}
              >
                عربي
              </Button>
            </Space>
          </div>
        </div>
        <div className={cs('flex-1')}>{/* <div className={cs(styles['mask_r'])}></div> */}</div>
      </div>
    </div>
  )
}

export default Dashboard
